package es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Before;
import org.junit.Test;

public class FindDocs {

    private RestHighLevelClient client;

   @Test
   public void findDocs() throws Exception{
       findDoc();
   }
    @Before
    public void init(){
        HttpHost host = new HttpHost("localhost",9200);
        client = new RestHighLevelClient(RestClient.builder(host));
    }


    // 查询方法
    public void findDoc() throws Exception {
        // 1. 创建 SearchRequest，指定要查询的索引
        SearchRequest searchRequest = new SearchRequest("test"); // 替换为你的索引名

        // 2. 创建查询条件：使用 match 查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("content", "go"); // 替换字段名和值

        // 3. 构建查询请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(matchQueryBuilder); // 设置查询条件
        searchRequest.source(sourceBuilder); // 将查询条件设置到 SearchRequest 中

        // 4. 执行查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // 5. 处理返回结果
        System.out.println("Total Hits: " + searchResponse.getHits().getTotalHits().value);
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            System.out.println("Document: " + hit.getSourceAsString());
        }
    }

}
